import { getToken, setToken, removeToken } from "@/utils/auth"
import { login, logout, getInfo } from '@/api/user'
import { resetRouter } from '@/router'

const getDefaultState = () => {
    return {
        token: getToken(),
        username: '',
        avatar: '',
        uid: '',
        userinfo: {
            username: '',
            uid: '',
            avatar: '',
            isLogin: false,
            token: getToken()
        }
    }
}


const state = getDefaultState()

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_USER: (state, payload) => {
      state.userinfo = payload
    },
    SET_NAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    }
}

const actions = {
      // user login
  login({ commit }, userInfo) {
    const { uid, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ uid: uid.trim(), password: password }).then(response => {
        console.log(response)
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('认证失败, 请重新登录！')
        }

        const { username, avatar, uid } = data
        const userinfo = { username, avatar, uid}

        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        commit('SET_UID', uid)
        commit('SET_USER', userinfo)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}